package com.xc.freeapp.util;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.xc.freeapp.entity.Hospital;
import com.xc.freeapp.entity.PicturesControl;
import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.service.HospitalService;
import com.xc.freeapp.service.impl.PicturesControlService;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import sun.misc.BASE64Decoder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

@SuppressWarnings({ "restriction" })
@Component

public class QiniuUpload {
	private static Logger log = Logger.getLogger(QiniuUpload.class);
	private static  String ACCESS_KEY="zZrGSNPqZLzOLE7yAmczl9boRfZj_KV0DvYfh-IE";
	private static  String SECRET_KEY="19HTr-Vv1E9qz_2L-o7BW5M0WRuHCGSrIG1yTiGH";
	private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	private static UploadManager uploadManager = new UploadManager();
	private static BucketManager bucketManager = new BucketManager(auth);
	private static SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");
	private static String qn_namespace ="";//上传空间设置
	private static String qn_domain= "";//域名设置  换成自己的网站域名
	
	private static QiniuUpload qiniuUpload;

	@PostConstruct
	public void init() {
		qiniuUpload = this;
		qiniuUpload.picturesControlService = this.picturesControlService;
		qiniuUpload.hospitalService=this.hospitalService;
	}
	@Autowired
	private HospitalService hospitalService;
	
	@Autowired
	PicturesControlService picturesControlService;
	
	public static String getQn_domain() {
		return qn_domain;
	}
	//预处理
	static{
		ResourceBundle bundle = ResourceBundle.getBundle("qiniucloud");
		ACCESS_KEY=bundle.getString("ACCESS_KEY");
		SECRET_KEY=bundle.getString("SECRET_KEY");
		qn_namespace = bundle.getString("qn_namespace");
		qn_domain = bundle.getString("qn_domain");
	}
	
	// 简单上传，使用默认策略
	public static String getUpToken0(){
	    return auth.uploadToken(qn_namespace).trim();
	}
	public static void delete(String key){
		try{
			bucketManager.delete(qn_namespace, key);
		}catch(QiniuException e){
			Response r = e.response;
			log.error(r.toString());// 请求失败时简单状态信息
		}
		
	}
	/**
	 * 文件保存
	 * @param request

	 */
	public static List<String> uploadRequestFiles(HttpServletRequest request, String upToken) throws Exception{

		String type=(String) request.getParameter("imgtype");   // imgtype
		String appid=(String) request.getParameter("appid");   // appid

		List<String> list = new ArrayList<String>();
		Map<String,MultipartFile> filemap =null;
		if(request instanceof MultipartHttpServletRequest) {
			filemap = ((MultipartHttpServletRequest) request).getFileMap();
		}
		for (Map.Entry<String,MultipartFile> entry : filemap.entrySet()) {
			MultipartFile multipartFile = entry.getValue();
			InputStream inputStream = multipartFile.getInputStream();

			byte[] data = IOUtils.toByteArray(inputStream);
			String filekey= upload(data, upToken, Integer.valueOf(appid));
			list.add(filekey);
		}
		return list;
	}
	/***
	 * 直接上传文件对象
	 * @return filename  不为空"" 表示上传成功
	 * @throws Exception
	 */
	public static String upload(File file, String upToken,Integer appId) throws Exception{
		String filename = "";
		Hospital hospital = qiniuUpload.hospitalService.selectByPrimaryKey(appId);
		String filenamekey = getKey(hospital.getAppid());
		try{
			PicturesControl picturesControl = new PicturesControl();
			picturesControl.setAppid(appId);
			picturesControl.setImgname(filenamekey);
			picturesControl.setDelflag("t");
			picturesControl.setImgtype("app");
			picturesControl.setCreatetime(new Date());
			qiniuUpload.picturesControlService.insertSelective(picturesControl);
		}catch(Exception e){
			log.error("上传图片插入到数据库出错"+e.getMessage());
		}
		
		
		
		try {
			Response res = uploadManager.put(file, filenamekey, upToken);
			log.info(res+"\r\n"+res.bodyString());
			if(res.isOK()){
				filename=filenamekey;
			}
		} catch (QiniuException e) {
			Response r = e.response;
			log.error(r.toString());// 请求失败时简单状态信息
			BaseException.throwBaseException(Constant.qiniu_uploaderror);
		}
		return filename;
	}
	
	/**
	 *根据客户端base64编码处理的字符串进行上传
	 * @return filename 不为空"" 表示上传成功
	 * */
	public static String upload(String pictureBuffer,String upToken,Integer appId) throws Exception{
		log.info("开始上传图片!");
		String filename ="";
		try {
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] decoderBytes = decoder.decodeBuffer(pictureBuffer.toString());
			filename = upload(decoderBytes, upToken,appId);
		} catch (IOException e) {
			log.error("图片上传出错!");
			e.printStackTrace();
		}
		return filename;
	}
	
	/**
	 * 上传内存中数据
	 * @return filename 不为空"" 表示上传成功
	 * */
	public static String upload(byte[] data, String upToken,Integer appId) throws Exception{
		String filename = "";
		Hospital hospital = qiniuUpload.hospitalService.selectByPrimaryKey(appId);
		String filenamekey = getKey(hospital.getAppid());
	
		try{
			PicturesControl picturesControl = new PicturesControl();
			picturesControl.setAppid(appId);
			picturesControl.setImgname(filenamekey);
			picturesControl.setDelflag("t");
			picturesControl.setImgtype("app");
			picturesControl.setCreatetime(new Date());
			qiniuUpload.picturesControlService.insertSelective(picturesControl);
		}catch(Exception e){
			e.printStackTrace();
			log.error("上传图片插入到数据库出错"+e.getMessage());
		}
		try {
			Response res = uploadManager.put(data, filenamekey, upToken);
			log.info(res+"\r\n"+res.bodyString());
			if(res.isOK()){
				filename=filenamekey;
			}
		} catch (QiniuException e) {
			Response r = e.response;
			log.error(r.toString());// 请求失败时简单状态信息
			BaseException.throwBaseException(Constant.qiniu_uploaderror);
		}
		return filename;
		
	}
	
	/**
	 * 获取key 即上传文件名 
	 * 		不保留文件后缀
	 */
	public static String getKey(Integer appId){
		Date date =new Date();
		String key = "usr_"+appId+"_app_"+simpleDateFormat.format(date)+ new Random().nextInt(100);
		return key;
	}
	
	/**
	 * 获取文件下载地址
	 */
	public String getDownloadUrl(String filenamekey){
		String ret = auth.privateDownloadUrl("http://"+qn_domain+"/"+filenamekey);
		return ret;
	}
	
	
	
	//测试用
	public byte[] getByPath(String path){
		FileInputStream a =null;
		byte[] a2b =null;
		try {
			a =  new FileInputStream(new File(path));
			ByteArrayOutputStream out = new ByteArrayOutputStream();  
	        byte[] buff = new byte[1024];  
	        int i = 0;  
	        while ((i = a.read(buff, 0, 100)) > 0) {  
	            out.write(buff, 0, i);  
	        }  
	        a2b = out.toByteArray();  
		} catch (Exception e) {}
		return a2b;
	}

}
